package com.imgrate.migration.scheduler;

import com.imgrate.migration.entity.BackupTask;
import com.imgrate.migration.service.BackupService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@RequiredArgsConstructor
@Slf4j
public class BackupScheduler {
    
    private final BackupService backupService;
    
    /**
     * 每分钟检查一次待执行的备份任务
     */
    @Scheduled(fixedRate = 60000) // 每分钟执行一次
    public void executePendingBackupTasks() {
        try {
            log.info("开始检查待执行的备份任务");
            
            // 获取待执行的备份任务
            List<BackupTask> pendingTasks = backupService.getPendingTasks();
            
            if (pendingTasks.isEmpty()) {
                log.info("没有待执行的备份任务");
                return;
            }
            
            log.info("发现 {} 个待执行的备份任务", pendingTasks.size());
            
            // 执行每个待执行的备份任务
            for (BackupTask task : pendingTasks) {
                try {
                    log.info("开始执行备份任务: {} (ID: {})", task.getTaskName(), task.getId());
                    backupService.executeBackup(task.getId());
                    log.info("备份任务执行完成: {} (ID: {})", task.getTaskName(), task.getId());
                } catch (Exception e) {
                    log.error("执行备份任务失败: {} (ID: {}), 错误: {}", 
                        task.getTaskName(), task.getId(), e.getMessage(), e);
                }
            }
        } catch (Exception e) {
            log.error("检查待执行备份任务时发生错误: {}", e.getMessage(), e);
        }
    }
}